package com.jyy.prefabricated.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.dto.StudentAchievementDto;
import com.jyy.prefabricated.entity.StudentAchievement;
import com.jyy.prefabricated.entity.SysUser;
import com.jyy.prefabricated.enums.UserTypeEnum;
import com.jyy.prefabricated.service.StudentAchievementService;
import com.jyy.prefabricated.utils.ExcelUtil;
import com.jyy.prefabricated.utils.UserUtils;
import junit.framework.Test;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 学生成绩表(StudentAchievement)表控制层
 *
 * @author mrl
 * @since 2021-07-07 16:19:15
 */
@Slf4j
@RequestMapping("/api")
@RestController
public class StudentAchievementController {
    /**
     * 服务对象
     */
    @Resource
    private StudentAchievementService studentAchievementService;
    @Resource
    private UserUtils userUtils;

    @GetMapping("/studentAchievement")
    public AjaxResult selectStudentAchievement(StudentAchievementDto studentAchievementDto) {
        Page page = new Page(studentAchievementDto.getPageNum(), studentAchievementDto.getPageSize());
        //PageHelper.startPage(studentAchievementDto.getPageNum(), studentAchievementDto.getPageSize());
        List<StudentAchievement> studentAchievements = studentAchievementService.selectMyAchievement(studentAchievementDto);
        page.setTotal(studentAchievements.size());
        //计算当前需要显示的数据下标起始值
        int startIndex = (studentAchievementDto.getPageNum() - 1) * studentAchievementDto.getPageSize();
        int endIndex = Math.min(startIndex + studentAchievementDto.getPageSize(), studentAchievements.size());
        //从链表中截取需要显示的子链表，并加入到Page
        page.addAll(studentAchievements.subList(startIndex, endIndex));
        //以Page创建PageInfo
        PageInfo result = new PageInfo<>(page);
        //PageInfo<StudentAchievement> result = new PageInfo<>(studentAchievements);
        return AjaxResult.success(result);
    }

    @GetMapping("/myAchievement")
    public AjaxResult selectMyAchievement(StudentAchievementDto studentAchievementDto) {
        SysUser user = userUtils.getCurrentUser();
        studentAchievementDto.setUserType(user.getUserType());
        if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
            studentAchievementDto.setBuyId(user.getTrainingOrganization().getId());
            studentAchievementDto.setRegistrationType(2);
        } else if (UserTypeEnum.STUDENT.getValue().equals(user.getUserType())) {
            studentAchievementDto.setStudentId(user.getStudent().getId());
            studentAchievementDto.setRegistrationType(1);
        } else {
            return AjaxResult.success(null);
        }
        PageHelper.startPage(studentAchievementDto.getPageNum(), studentAchievementDto.getPageSize());
        List<StudentAchievement> studentAchievements = studentAchievementService.selectMyAchievement(studentAchievementDto);
        PageInfo<StudentAchievement> result = new PageInfo<>(studentAchievements);
        return AjaxResult.success(result);
    }

    @GetMapping("/historyAchievement")
    public AjaxResult selectHistoryAchievement(StudentAchievementDto studentAchievementDto) {
        List<StudentAchievement> studentAchievements = studentAchievementService.selectHistoryAchievement(studentAchievementDto);
        return AjaxResult.success(studentAchievements);
    }

    /**
     * 获取学员成绩详情
     *
     * @param categoryId
     * @param studentId
     * @return
     */
    @GetMapping("/studentAchievement/{categoryId}/{studentId}")
    public AjaxResult selectById(@PathVariable Integer categoryId, @PathVariable Integer studentId) {
        log.info("Rest request to find student by id:{}", categoryId, studentId);
        StudentAchievement result = studentAchievementService.queryByCategoryIdId(categoryId, studentId);
        return AjaxResult.success(result);
    }

    /**
     * 更新学员
     *
     * @param dto
     * @return
     */
    @PutMapping("/studentAchievement")
    public AjaxResult update(@RequestBody StudentAchievementDto dto) {
        log.info("Rest request to update student:{}", dto);
        if (dto.getCategoryId() == null || dto.getStudentId() == null) {
            //throw new CustomException("导入学员信息为空");
            return AjaxResult.error(-1, "请传入修改项目分类和学员");
        }
        int result = studentAchievementService.updateAchieve(dto);
        if (result == -1) {
            return AjaxResult.error("请先导入该学员线下成绩");
        }
        return AjaxResult.success();
    }

    /**
     * 录入线下成绩
     *
     * @param file
     * @return
     */
    @PostMapping("/studentAchievement")
    public AjaxResult insert(MultipartFile file) {

        AjaxResult result = studentAchievementService.importStudentAchieve(file);
        return result;
    }

    /**
     * 导出报名信息
     */

    @GetMapping("/studentAchievement-excel")
    public void downloadExcel(StudentAchievementDto studentAchievementDto, HttpServletResponse response) {
        List<StudentAchievement> studentAchievements = studentAchievementService.selectMyAchievement(studentAchievementDto);
        downloadExcel(studentAchievements, response);
    }

    /**
     * 导出excel
     *
     * @param list
     * @param response
     */
    public void downloadExcel(List<StudentAchievement> list, HttpServletResponse response) {
        String title = "考试成绩表";
        Workbook workbook = writeDataToExcel(list);
        try {
            ExcelUtil.downloadExcel(response, workbook, title);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将数据写入excel
     *
     * @param list
     * @return
     */
    public Workbook writeDataToExcel(List<StudentAchievement> list) {
        String[] titleList = {"项目分类", "报名人", "身份证号", "线上成绩", "线下成绩", "是否合格"};
        InputStream is = Test.class.getClassLoader().getResourceAsStream("templates/studentAchievement.xlsx");
        //检查模板文件
        Workbook workbook = null;
        try {
            workbook = new XSSFWorkbook(is);
            if (workbook != null) {
                for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                    //获得当前sheet工作表
                    Sheet sheet = workbook.getSheetAt(sheetNum);
                    if (sheet == null) {
                        continue;
                    }
                    //获得当前sheet的结束行
                    int lastRowNum = sheet.getLastRowNum();
                    Row firstRow = sheet.getRow(lastRowNum - 1);
                    int columnNum = 0;
                    if (firstRow != null) {
                        columnNum = firstRow.getPhysicalNumberOfCells();
                    }
                    for (int j = 0; j < columnNum; j++) {
                        Cell cell = firstRow.getCell(j); //第1行,第j列
                        String cellValue = cell.getStringCellValue();
                        System.out.println(cellValue);
                    }
                    Row row = sheet.createRow(lastRowNum + 1);
                    //创建内容
                    Cell dataCell = null;
                    int count = 0;
                    for (int i = 0; i < list.size(); i++) {
                        row = sheet.createRow(lastRowNum + i + 1);
                        for (int j = 0; j < titleList.length; j++) {
                            dataCell = row.createCell(j);
                            if (j == 0) {
                                String value = list.get(i).getCategoryName();
                                dataFormat(dataCell, value);
                            } else if (j == 1) {
                                String value = list.get(i).getName();
                                dataFormat(dataCell, value);
                            } else if (j == 2) {
                                String value = list.get(i).getIdCard();
                                dataFormat(dataCell, value);
                            } else if (j == 3) {
                                if (list.get(i).getGradeOne() != null) {
                                    String value = list.get(i).getGradeOne().toString();
                                    dataFormat(dataCell, value);
                                } else {
                                    dataFormat(dataCell, null);
                                }

                            } else if (j == 4) {
                                if (list.get(i).getGradeTwo() != null) {
                                    if (list.get(i).getGradeTwo() == 1) {
                                        String value = "合格";
                                        dataFormat(dataCell, value);
                                    } else {
                                        String value = "不合格";
                                        dataFormat(dataCell, value);
                                    }
                                } else {
                                    dataFormat(dataCell, null);
                                }

                            } else if (j == 5) {
                                if (list.get(i).getQualified() == 1) {
                                    String value = "合格";
                                    dataFormat(dataCell, value);
                                } else {
                                    String value = "不合格";
                                    dataFormat(dataCell, value);
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }

    /**
     * 单元格值格式化
     *
     * @param dataCell
     * @param obj
     */
    private static void dataFormat(Cell dataCell, Object obj) {
        if (obj == null) {
            dataCell.setCellValue("");
        } else {
            if (obj instanceof String) {
                dataCell.setCellValue((String) obj);
            } else if (obj instanceof Double) {
                dataCell.setCellValue((Double) obj);
            } else if (obj instanceof Float) {
                dataCell.setCellValue((Float) obj);
            } else if (obj instanceof Long) {
                dataCell.setCellValue((Long) obj);
            } else if (obj instanceof Boolean) {
                dataCell.setCellValue((Boolean) obj);
            } else if (obj instanceof Date) {
                Date d = (Date) obj;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String createDate = sdf.format(d);
                dataCell.setCellValue(createDate);
            }
        }
    }

}